package cn.lg.soar.core.annotations.constraints;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 验证是否是一个有效的id
 * @author luguoxiang
 * @date 2021/9/28
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(value = RetentionPolicy.RUNTIME)
@Constraint(validatedBy= Id.Validator.class)
public @interface Id {

    String message() default "无效id";

    boolean required() default true;

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * 校验器
     */
    class Validator implements ConstraintValidator<Id, Number> {

        private boolean required;

        @Override
        public void initialize(Id ca) {
            this.required = ca.required();
        }

        @Override
        public boolean isValid(Number id, ConstraintValidatorContext constraintValidatorContext) {
            if (id == null) {
                return !this.required;
            }
            return id.longValue() > 0L;
        }

    }

}
